<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-form :inline="true" :model="formPageParam" class="user-search">
      <el-form-item label="搜索：">
        <el-input size="small" v-model="formPageParam.permissionCode" placeholder="输入权限编码"></el-input>
      </el-form-item>
      <el-form-item label="">
        <el-input size="small" v-model="formPageParam.permissionName" placeholder="输入权限名称"></el-input>
      </el-form-item>
      <el-form-item label="角色：">
        <el-select size="small" v-model="formPageParam.roleId" placeholder="请选择">
          <el-option selected label="请选择" value="0"></el-option>
          <el-option v-for="param in roleList" :key="param.id" :label="param.name" :value="param.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
        <el-button size="small" type="primary" icon="el-icon-plus" @click="handleEdit()">添加</el-button>
        <el-button size="small" type="primary" icon="el-icon-plus" @click="rolePermission()">配置权限</el-button>
      </el-form-item>
    </el-form>
    <el-table size="small" @selection-change="selectChange" :data="listData" highlight-current-row v-loading="loading"
              border element-loading-text="拼命加载中" style="width: 100%;">
      <el-table-column align="center" type="selection" width="60">
      </el-table-column>
      <el-table-column sortable prop="permissionCode" label="权限编码" width="120">
      </el-table-column>
      <el-table-column sortable prop="permissionName" label="权限名称" width="120">
      </el-table-column>
      <el-table-column sortable prop="updateTime" label="修改时间" width="180">
        <template slot-scope="scope">
          <div>{{scope.row.updateTime|timestampToTime}}</div>
        </template>
      </el-table-column>
      <el-table-column sortable prop="updateByName" label="修改人" width="120">
      </el-table-column>
      <el-table-column align="center" label="操作" min-width="300">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="deletePermission(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <Pagination v-bind:child-msg="pageParam" @callFather="refreshParentPage"></Pagination>
    <el-dialog :title="title" :visible.sync="editFormVisible" width="30%" @click="closeDialog">
      <el-form label-width="120px" :model="editForm" :rules="rules" ref="editForm">
        <el-form-item label="权限编码" prop="permissionCode">
          <el-input size="small" v-model="editForm.permissionCode" auto-complete="off" placeholder="权限CODE"></el-input>
        </el-form-item>
        <el-form-item label="权限名称" prop="permissionName">
          <el-input size="small" v-model="editForm.permissionName" auto-complete="off" placeholder="权限名称"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog">取消</el-button>
        <el-button size="small" type="primary" :loading="loading" class="title" @click="submitForm('editForm')">保存
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from '../../components/Pagination'
import {getRequest, postRequest} from '../../utils/api'
export default {
  data () {
    return {
      loading: false,
      editFormVisible: false,
      title: '添加',
      editForm: {
        id: '',
        permissionName: '',
        permissionCode: ''
        // token: localStorage.getItem('logintoken')
      },
      rules: {
        permissionName: [
          {required: true, message: '请输入权限名称', trigger: 'blur'}
        ],
        permissionCode: [
          {required: true, message: '请输入权限编码', trigger: 'blur'}
        ]
      },
      formPageParam: {
        page: 1,
        limit: 10,
        permissionName: '',
        permissionCode: '',
        roleId: '0'
        // token: localStorage.getItem('logintoken')
      },
      selectData: [],
      roleList: [],
      listData: [],
      pageParam: {
        currentPage: 1,
        pageSize: 10,
        total: 10
      }
    }
  },
  components: {
    Pagination
  },
  watch: {},
  created () {
    this.getData(this.formPageParam)
    this.getRoleList()
  },
  methods: {
    getData (parameter) {
      this.loading = true
      getRequest('/system/permission/page', parameter).then(resp => {
        this.loading = false
        if (resp && resp.code === 0 && resp.data) {
          this.listData = resp.data.records
          this.pageParam.currentPage = this.formPageParam.pageNum
          this.pageParam.pageSize = this.formPageParam.pageSize
          this.pageParam.total = resp.data.total
        }
        // eslint-disable-next-line handle-callback-err
      }).catch(err => {
        this.loading = false
        this.$message.error('获取权限列表失败，请稍后再试！')
      })
    },
    getRoleList () {
      getRequest('/system/role/select').then(resp => {
        this.loading = false
        if (resp && resp.code === 0 && resp.data) {
          this.roleList = resp.data
        } else {
          this.$message({
            type: 'info',
            message: resp.msg
          })
        }
      })
    },
    refreshParentPage (param) {
      this.formPageParam.pageNum = param.currentPage
      this.formPageParam.pageSize = param.pageSize
      this.getData(this.formPageParam)
    },
    search () {
      this.getData(this.formPageParam)
    },
    handleEdit: function (index, row) {
      this.editFormVisible = true
      if (row !== undefined && row !== 'undefined') {
        this.title = '修改'
        this.editForm.id = row.id
        this.editForm.permissionName = row.permissionName
        this.editForm.permissionCode = row.permissionCode
      } else {
        this.title = '添加'
        this.editForm.id = ''
        this.editForm.permissionName = ''
        this.editForm.permissionCode = ''
      }
    },
    submitForm (editData) {
      this.$refs[editData].validate(valid => {
        if (valid) {
          postRequest('/system/permission/save', this.editForm).then(resp => {
            this.editFormVisible = false
            this.loading = false
            if (resp && resp.code === 0 && resp.data) {
              this.getData(this.formPageParam)
              this.$message({
                type: 'success',
                message: '保存权限成功！'
              })
            } else {
              this.$message({
                type: 'info',
                message: resp.msg
              })
            }
            // eslint-disable-next-line handle-callback-err
          }).catch(err => {
            this.editFormVisible = false
            this.loading = false
            this.$message.error('保存权限失败，请稍后再试！')
          })
        }
      })
    },
    deletePermission (index, row) {
      this.$confirm('确定要删除吗?', '信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let deleteParam = {'id': row.id}
        postRequest('/system/permission/delete', deleteParam).then(resp => {
          if (resp && resp.code === 0 && resp.data) {
            this.$message({
              type: 'success',
              message: '权限已删除！'
            })
            this.getData(this.formPageParam)
          } else {
            this.$message({
              type: 'info',
              message: resp.msg
            })
          }
          // eslint-disable-next-line handle-callback-err
        }).catch(err => {
          this.loading = false
          this.$message.error('删除权限失败,请稍后再试！')
        })
      })
    },
    selectChange (val) {
      this.selectData = val
    },
    rolePermission () {
      let params = {
        roleId: '',
        permIds: []
      }
      if (this.formPageParam.roleId === '0') {
        this.$message({
          type: 'info',
          message: '请选择角色'
        })
        return false
      }
      debugger
      let selectedList = this.selectData
      if (selectedList.length === 0) {
        this.$message({
          type: 'info',
          message: '请选择权限！'
        })
        return false
      }
      let ids = []
      for (let i = 0; i < selectedList.length; i++) {
        ids.push(selectedList[i].id)
      }
      params.roleId = this.formPageParam.roleId
      params.permIds = ids
      postRequest('/system/permission/bindRole', params).then(resp => {
        if (resp && resp.code === 0 && resp.data) {
          this.$message({
            type: 'success',
            message: '配置权限成功！'
          })
          this.getData(this.formPageParam)
        } else {
          this.$message({
            type: 'info',
            message: resp.msg
          })
        }
        // eslint-disable-next-line handle-callback-err
      }).catch(err => {
        this.loading = false
        this.$message.error('配置权限失败！')
      })
    },
    closeDialog () {
      this.editFormVisible = false
    }
  }
}
</script>

<style scoped>
  .user-search {
    margin-top: 20px;
    text-align: left;
  }
</style>
